<?php
/*=============================================================================
|| ##################################################################
||	phpFoX Konsort
|| ##################################################################
||
||	Copyright		: (C) 2005-2007 PHPFOX Limited a Reality Fox Creation
||	Contact			: info@phpfox.com
||
||	- phpFoX and all of its source code and files are protected by Copyright Laws.
||
||	- The license for phpFoX permits you to install this software on a single domain (.com, .org, .net, etc.).
||
||	- You may also not remove this copyright screen which shows the copyright information and credits for phpFoX (RealityFOX Creations).
||
||	- phpFoX Konsort is NOT a FREE software - http://www.phpfox.com/license/
||
|| ##################################################################
=============================================================================*/

/* $File: ./include/classes/file/File.class.php, $Author:  $ */

/** CFile (Common File) is an abstraction of uploadable/downloadable file
 */
class CFile extends Object
{
    // filesize
    var $nSize;

    // mime type
    var $sMimeType;

    // full path to file
    var $sPath;

    // uploading limits
    var $aLimits = array();

    // type of file(exstension)
    var $sType;

    // Real name of uploaded file
    var $sRealName = '';

    function CFile()
    {
        $this->aLimits['FILE_MAX_SIZE'] = App::getParam('file.max_size');
    }

    function getName()
    {
        return basename($this->sPath);
    }

    function loadInfo($sPath)
    {
        if('' == $this->sRealName)
        {
            $this->sRealName = $sPath;
        }

        $this->sPath = $sPath;

        if (! file_exists($sPath))
        {
            return $this->_addError('file.not_exist', $sPath);
        }

        $this->nSize = filesize($this->sPath);
        if (!$this->nSize)
        {
            return $this->_addError('file.not_exist', $this->sRealName);
        }

        if (! $this->sType)
        {
            $this->sType = subStr($this->sPath, strrpos($this->sPath, '.'));
        }

        return true;
    }

	function getContent($sUrl)
	{
		if ( function_exists('curl_init') )
		{
			$c = curl_init();
			curl_setopt($c, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
			curl_setopt($c, CURLOPT_URL, $sUrl);
			curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
			$sResult = curl_exec($c);
			curl_close($c);
			return $sResult;
		}
		else
		{
			$sData = @file_get_contents($sUrl);
			return $sData;
		}
	}

	function copyContent($sFile, $sSave)
	{
		@ob_start();
		@copy($sFile, $sSave);
		@ob_end_flush();

		if ( file_exists($sSave) )
		{
			return true;
		}

		return false;
	}

    function getFileType($filename)
    {
		$filename = strtolower($filename);
		$exts = split("[/\\.]", $filename);
		$n = count($exts)-1;
		$exts = $exts[$n];
		return $exts;
    }

    function move($sDest)
    {
        @rename($this->sPath, $sDest);
        $this->sPath = $sDest;
    }

    // $sDestPath (with /)
    function upload($sFormItem, $sDestPath, $sDestName='', $sDestExt='', $iPerm = 0644)
    {
        $aFile = CFile::_buildFile($sFormItem);
        $this->sMimeType = $aFile['type'];
        $this->sRealName = $aFile['name'];
        $this->sType = ($sDestExt ? $sDestExt : subStr($aFile['name'], strrpos($aFile['name'], '.') + 1));

        if (!$this->loadInfo($aFile['tmp_name']))
        {
            return false;
        }
        if (!$this->_checkLimits())
        {
            return false;
        }
        $this->sType = $sDestExt;
        if (!is_uploaded_file($this->sPath))
        {
            return $this->_addError('file.not_uploaded', $aFile['name']);
        }
        $sDest = $sDestName ? $sDestPath.$sDestName : $sDestPath.substr($aFile['name'], 0, strrpos($aFile['name'], '.'));
        $sDest .= '.';
        $sDest .= ($sDestExt) ? $sDestExt : $this->sType;
        if (!move_uploaded_file($this->sPath, $sDest))
        {
            return $this->_addError('file.not_moved', $aFile['name']);
        }
        $this->sPath = $sDest;

        @chmod($this->sPath, $iPerm);

		if ( App::getUser('id') )
		{
			App::updateUserSpace();
		}

        return $aFile;
    }

    //@todo implement
    function _buildFile($sFormItem)
    {
        $aFile = array();
        if (!strpos($sFormItem, ']'))
        {
            $aFile = $_FILES[$sFormItem];
        }
        elseif (preg_match('/^(.+)\[(.+)\]$/', $sFormItem, $aM))
        {
            $aFile['name']     = $_FILES[$aM[1]]['name'][$aM[2]];
            $aFile['type']     = $_FILES[$aM[1]]['type'][$aM[2]];
            $aFile['tmp_name'] = $_FILES[$aM[1]]['tmp_name'][$aM[2]];
            $aFile['error']    = $_FILES[$aM[1]]['error'][$aM[2]];
            $aFile['size']     = $_FILES[$aM[1]]['size'][$aM[2]];
        }
        else // fatal error
        {
            $this->_addError('file.invalid_input_name', $sFormItem, true);
        }
        return $aFile;
    }

    function _checkLimits()
    {
        if ($this->aLimits['FILE_MAX_SIZE'] and $this->nSize >= $this->aLimits['FILE_MAX_SIZE'])
        {
            return $this->_addError('file.max_size', array($this->nSize, ($this->aLimits['FILE_MAX_SIZE'] > 0)?$this->aLimits['FILE_MAX_SIZE']:0));
        }
        return true;
    }

    function readDir($sDir, $mExtensions = '')
    {
        $aExtensions = array();
        if (!is_array($mExtensions))
        {
            $aExtensions[] = $mExtensions;
        }
        else
        {
            $aExtensions = $mExtensions;
        }
        $aDirs = array();
        if ($hDir = opendir($sDir))
        {
           while (false !== ($sFile = readdir($hDir)))
           {
               if (($sFile == '.') || ($sFile == '..'))
               {
                   continue;
               }
               if ($aExtensions)
               {
                   $sExtension = pathinfo($sFile, PATHINFO_EXTENSION);
                   if (!in_array($sExtension, $aExtensions))
                   {
                       continue;
                   }
               }
               $aDirs[$sFile] = is_dir($sDir.$sFile);
           }
           closedir($hDir);
           return $aDirs;
        }
        return false;
    }

    /**
     * Checks if path is writable
     *
     * @param string $sPath Path to file or directory
     * @return boolean
     *
     */
    function isWritable($sPath)
    {
        clearstatcache();
        /*if (!file_exists($sPath))
        {
            if (!@mkdir($sPath))
            {
                return false;
            }
        }
        clearstatcache();*/

        /**
         * Checking if writable using standart method on non-windows OS
         */
        //$sPath = strip_tags($sPath);
        //$sPath = substr($sPath, 1, strlen($sPath) - 2);

        if (!is_writable($sPath))
        {
            if (!stristr(PHP_OS, "win"))
            {
                return false;
            }
        }

        /**
         * Checking if writable on windows OS
         */
        if (stristr(PHP_OS, "win"))
        {
            /**
             * need to check whether we can really create files in this directory or not
             */
            if (is_dir($sPath))
            {
                /**
                 * Trying to create a new file
                 */
                $fp = fopen($sPath . '/dummy.txt', 'w');
                if (!$fp)
                {
                    return false;
                }
                if (!fwrite($fp, 'test'))
                {
                    return false;
                }
                fclose($fp);
                /**
                 * clean up after ourselves
                 */
                unlink($sPath . '/dummy.txt');
            } else
            {
                /**
                 * If path is a file, trying to rename it
                 */
                if (!rename($sPath, $sPath . '__'))
                {
                    return false;
                }
                /**
                 * Renaming back
                 */
                rename($sPath . '__', $sPath);
            }
        }
        return true;
    }

    function deleteRecursiveFolder($sFolder)
    {
        $hDir = opendir($sFolder);
        while (false !== ($sItem = readdir($hDir)))
        {
            if (($sItem != '.') && ($sItem != '..') && ($sItem != 'index.html') && ($sItem != '.htaccess') && ($sItem != '.svn'))
            {
                $sItemPath = $sFolder.'/'.$sItem;
                if (is_file($sItemPath))
                {
                    unlink($sItemPath);
                }
                if (is_dir($sItemPath))
                {
                    CFile::deleteRecursiveFolder($sItemPath);
                    rmdir($sItemPath);
                }
            }
        }
        closedir($hDir);
        return true;
    }
}
?>